<?php

namespace App\V3\V3_2\Controllers;

use App\V3\V3_2\Models\SellGoodsDetailBatchModel;
use App\V3\V3_2\Models\SellGoodsDetailModel;
use App\V3\V3_2\Models\SellModel;
use App\V3\V3_2\Models\SellPackageBatchModel;
use App\V3\V3_2\Models\SellPackageDetailModel;
use App\V3\V3_2\Models\SellPayRecordModel;
use App\V3\V3_2\Services\OutInRepealService;
use App\V3\V3_2\Services\SellService;
use App\Helper\Utils\TimeUtil;
use App\Rules\JsonArray;
use App\Services\IncomeExpensesService;
use App\V3\V3_2\Models\SellDriverModel;
use App\V3\V3_2\Models\SellOtherChargesModel;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2\Services\SalesReturnService;

class SellController extends BaseController
{
    //销售序列号列表
    public function sellSerialNumber(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_type_id' =>'required',//页面大小

            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'materiel_type_id.required' => '参数`商品id`缺失',
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return $this->success(SalesReturnService::salesReturnSerialNumber($request->materiel_type_id,$status = 1,$data));
    }
    /**
     * 添加销售单
     * change 在 2021/11/1 16:46 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'customer_name' =>'required',//客户姓名
           /*  'discount' =>'integer|min:0',//折扣 ：百分比
            'tax_rate' =>'integer|min:0',//税率 ：百分比 */
            'is_zero_suppression' =>[
                'required',
                Rule::In([0,1]),
            ],//是否抹零：0-否 1-是
            'final_money' =>'integer|min:0',//实际应收金额（即折扣或抹零后价格）
            'deliver_goods_type' =>[
                Rule::In([1,2,3])
            ],//发货方式：1-自提 2-代发 3-送货
            'transport_type' =>[
                Rule::In([1,2,3,4])
            ],//运输方式：1-空运 2-海运 3-铁路 4-公路
            'consignee' =>'string',//收货人
            'phone' =>'string',//联系电话
            'address' =>'string',//地址
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'sell_date' =>'required|date',//销售时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            'real_money' =>'string',//实收金额（实际入账）
            'is_draft' =>[
                'required',
                Rule::In([0,1])
            ],//是否草稿：1-是 0-否
            'source' =>[
                Rule::In([0,1,2,3,4,5])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ],[
            'customer_name.required' => '请填写客户姓名',
            'goods_info.required' => '请填写商品信息',
         /*    'discount.integer' => '折扣仅能为数字',
            'discount.min' => '折扣最小只能为0',
            'tax_rate.integer' => '税率仅能为数字',
            'tax_rate.min' => '税率最小只能为0', */
            'is_zero_suppression.required' => '请选择是否抹零',
            'is_zero_suppression.in' => '您选择了未知的抹零方式',
            'final_money.integer' => '实际应收金额仅能为数字',
            'final_money.min' => '实际应收金额最小只能为0',
            'deliver_goods_type.in' => '您选择了未知的发货方式',
            'transport_type.in' => '您选择了未知的运输方式',
            'sell_date.required' => '请选择销售时间',
            'sell_date.date' => '销售时间不符合要求，请重新选择',
            'is_draft.required' => '请选择是否设置为草稿',
            'is_draft.in' => '选择了错误的草稿方式',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //报溢报损主单
        $mainInfo = $data;
        unset($mainInfo['goods_info']);
        unset($mainInfo['package_info']);
        $mainInfo['main_id'] = $this->getMainUserId();
        $mainInfo['user_id'] = $this->getUserId();
        $mainInfo['created_at'] = time();
        $mainInfo['sell_date'] = strtotime($data['sell_date']);
        $mainInfo['sell_time'] = strtotime(date('Y-m-d', strtotime($data['sell_date'])));
        $mainInfo['order_no'] = 'S'. $this->getMainUserId().TimeUtil::getMillisecond();//订单号

        $data['batch_title'] = $this->batchTitle();
//        //是否使用批次号；0:否;1:是;
//        if($this->getOutWay()) {
//            $result = SellsService::addWithBatch($mainInfo, $data);
//        }
//        else {
            $result = SellService::add($mainInfo, $data);
//        }

        return response()->json(
            $result
        );
    }

    /**
     * 销售单列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer|min:1',//当前页
            'repeal_status'=>[
                'required',
                Rule::In([0,1])
            ],//撤销状态：0-未撤销 1-已撤销
            'search_type'=>[
                'required',
                Rule::In([1,2,3,4,5,6,7,8])
            ],
            'status'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6])
            ]
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
            'repeal_status.required' => '`撤销状态`缺失',
            'repeal_status.in' => '`撤销状态`不合法',
            'search_type.required' => '`搜索类型`缺失',
            'search_type.in' => '`搜索类型`不合法',
            'status.required' => '`状态`缺失',
            'status.in' => '`状态`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if($this->getUserId() == $this->getMainUserId()){
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isShareSell()) {
                $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $userId['a.user_id'] = ['EQ' => $this->getUserId()];
            }
        }

        $info = SellService::list($userId, $data);

        return $this->success($info);
    }

    /**
     * 销售单详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 17:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required',//销售单主键id
        ],[
            'id.required' => '参数`销售单id`缺失'
        ]);

        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            SellService::detail(
                $request->id
            )
        );
    }

    /**
     * 删除
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/25 17:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required',//销售单主键
        ], [
            'id.required' => '参数`销售单id`缺失'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        SellModel::where('id', $data['id'])->update([
            'delete_flag' => 1
        ]);
        return $this->success();
    }

    /**
     * 编辑
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/26 14:51
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//主键id
//            'customer_name' =>'required',//客户姓名
            /* 'discount' =>'integer|min:0',//折扣 ：百分比
            'tax_rate' =>'integer|min:0',//税率 ：百分比 */
            'is_zero_suppression' =>[
                'required',
                Rule::In([0,1]),
            ],//是否抹零：0-否 1-是
            'final_money' =>'integer|min:0',//实际应收金额（即折扣或抹零后价格）
            'deliver_goods_type' =>[
                Rule::In([1,2,3])
            ],//发货方式：1-自提 2-代发 3-送货
            'transport_type' =>[
                Rule::In([1,2,3,4])
            ],//运输方式：1-空运 2-海运 3-铁路 4-公路
            'consignee' =>'string',//收货人
            'phone' =>'string',//联系电话
            'address' =>'string',//地址
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'sell_date' =>'required|date',//销售时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            'real_money' =>'string',//实收金额（实际入账）
            'is_draft' =>[
                'required',
                Rule::In([0,1])
            ],//是否草稿：1-是 0-否
            'source' =>[
                Rule::In([0,1,2,3,4,5])
            ]//订单来源:0-未知 1-安卓 2-ios 3-pc 4-微信小程序 5-抖音小程序
        ],[
            'id.required' => '参数`销售单id`缺失',
//            'customer_name.required' => '请填写客户姓名',
            'goods_info.required' => '请填写商品信息',
           /*  'discount.integer' => '折扣仅能为数字',
            'discount.min' => '折扣最小只能为0',
            'tax_rate.integer' => '税率仅能为数字',
            'tax_rate.min' => '税率最小只能为0', */
            'is_zero_suppression.required' => '请选择是否抹零',
            'is_zero_suppression.in' => '您选择了未知的抹零方式',
            'final_money.integer' => '实际应收金额仅能为数字',
            'final_money.min' => '实际应收金额最小只能为0',
            'deliver_goods_type.in' => '您选择了未知的发货方式',
            'transport_type.in' => '您选择了未知的运输方式',
            'sell_date.required' => '请选择销售时间',
            'sell_date.date' => '销售时间不符合要求，请重新选择',
            'is_draft.required' => '请选择是否设置为草稿',
            'is_draft.in' => '选择了错误的草稿方式',
            'source.in' => '未知的订单来源'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //报溢报损主单
        $mainInfo = $data;
        if(isset($mainInfo['sell_date'])) $mainInfo['sell_date'] = strtotime($data['sell_date']);
        if(isset($mainInfo['order_time'])) $mainInfo['order_time'] = strtotime($data['order_time']);
        if(isset($mainInfo['deliver_time'])) $mainInfo['deliver_time'] = strtotime($data['deliver_time']);
        $mainInfo['main_id'] = $this->getMainUserId();
        $mainInfo['user_id'] = $this->getUserId();

        $data['batch_title'] = $this->batchTitle();

        //是否使用批次号；0:否;1:是;
//        if($this->getOutWay()) {
//            $result = SellsService::editWithBatch($mainInfo, $data);
//        }
//        else {
            $result = SellService::edit($mainInfo, $data);
//        }

        return response()->json(
            $result
        );
    }

    /**
     * 收款
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/26 15:32
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMoney(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id'=>'required|integer',//销售单主键
            'money'=>'numeric|min:0',//收款金额
            'collection_time'=>'required|date',//收款时间
            'collection_account'=>'required|string',//收款账号
            'status'=>'required|integer',//收款状态：1-全部 2-部分
        ],[
            'money.numeric' => '金额异常，只能为数字，请重新输入',
            'money.min' => '金额不能低于0'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            $model = SellModel::where('id',$data['sell_id'])->first();//销售单信息
            $inMomey = SellPayRecordModel::where('sell_id',$data['sell_id'])->sum('expend');//已收款金额
            //全部收款
            if($data['status']==1){
                $model->pay_status = 2;
                $model->real_money = $model->final_money+$model->other_charges;
                $model->save();
                //支付完成更新商品支付状态
                SellGoodsDetailModel::where('sell_id',$data['sell_id'])->update(['pay_status'=>1]);
                //支付完成更新套餐支付状态
                SellPackageDetailModel::where('sell_id', $data['sell_id'])->update(['pay_status'=>1]);

                $money = ($model['final_money']+$model['other_charges'])-$inMomey;
            }else{//部分收款
                //收款超额检测
                if(($inMomey+$data['money'])>($model['final_money']+$model['other_charges'])){
                    return $this->fail('','超出剩余应付金额');
                }
                if(($inMomey+$data['money'])<($model['final_money']+$model['other_charges'])){
                    $model->real_money = $inMomey+$data['money'];
                    $model->pay_status = 1;
                }
                if(($inMomey+$data['money'])==($model['final_money']+$model['other_charges'])){
                    $model->pay_status = 2;
                    $model->real_money = $model->final_money+$model->other_charges;
                    //支付完成更新商品支付状态
                    SellGoodsDetailModel::where('sell_id',$data['sell_id'])->update(['pay_status'=>1]);
                    //支付完成更新套餐支付状态
                    SellPackageDetailModel::where('sell_id', $data['sell_id'])->update(['pay_status'=>1]);
                }
                $model->save();
                $money = $data['money'];
            }

            //收款记录
            $data['collection_time'] = strtotime($data['collection_time']);
            $data['created_at'] = time();
            $data['main_id'] = $this->getMainUserId();
            unset($data['status']);
            unset($data['money']);
            $data['expend'] = $money;
            SellPayRecordModel::insert($data);

            //账单记录
            IncomeExpensesService::tally(0,$model['order_no'],$money, $this->getMainUserId(), $model['sell_date']);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            Log::debug('销售单收款'.var_export($e->getMessage(), true));
            //异常响应
            return $this->fail($e->getMessage(),'销售单收款');
        }
    }

    /**
     * 重新下单
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/26 15:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgain(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ],[
            'id.required' => '参数`销售单id`缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['batch_title'] = $this->batchTitle();

        return response()->json(SellService::addAgain($data));
    }

    public function out(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//销售单主键id
            'status' => 'required|integer',//出入库状态：0-部分 1-全部
            'in_storage_time'=>'nullable|date_format:Y-m-d H:i:s',//出库时间
            'remark' => 'string',//备注
        ],[
            'id.required' => '参数`销售单id`缺失',
            'status.required' => '参数`出库状态`缺失',
            'in_storage_time.date_format' => '出库时间格式错误',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['out_way'] = $this->getOutWay();

//            if(!$data['out_way']) {
               /*  $result = OutInRepealService::outIn(
                    1,
                    $data['id'],
                    $data['status'],
                    empty($data['goods_info'])?'':$data['goods_info'],
                    empty($data['package_info'])?'':$data['package_info'],
                    $data
                );   */
                //序列号
        $result = SellService::sellOut(
            1,
            $data['id'],
            $data['status'],
            empty($data['goods_info'])?'':$data['goods_info'],
            empty($data['package_info'])?'':$data['package_info'],
            $data,
            $this->isUseShelf()
        );
//                $result = OutInRepealService::outInBySerial(
//                    1,
//                    $data['id'],
//                    $data['status'],
//                    empty($data['goods_info'])?'':$data['goods_info'],
//                    empty($data['package_info'])?'':$data['package_info'],
//                    $data,
//                    $this->isUseShelf()
//                    );
//            }else {
//                die;
//                $result = SellService::outWithBatch(
//                    $data['id'],
//                    $data['status'],
//                    empty($data['goods_info'])?'':$data['goods_info'],
//                    empty($data['package_info'])?'':$data['package_info'],
//                    $data,
//                    $this->isUseShelf()
//                );
//        }

        $this->log('销售单出库', $data);
        return response()->json(
            $result
        );
    }

    public function prepare(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ],[
            'id.required' => '销售单id缺失'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('销售单预出库', $data);

        return response()->json(
            SellService::prepare($data)
        );
    }

    public function repeal(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['out_way'] = $this->getOutWay();

//        if(!$data['out_way']) {
            $res = OutInRepealService::repeal($data['id'],1);
            if($res==0){
                return $this->fail('','商品被删除，无法撤销');
            }
            else if($res['code'] == 1) {
                return $this->fail('', $res['msg']);
            }

            if($res==1){
                return $this->success();
            }
//        }
//        else {
//            return response()->json(
//                SellService::repealWithBatch($data['id'])
//            );
//        }
    }

    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            SellService::payHistory($request->id)
        );
    }


    /**
     * 销售单设置批次号
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/24 17:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellAddBatch(Request $request)
    {
//参数验证
        $validator = Validator::make($data = $request->all(), [
            'info' => [
                'required',
                'json',
                new JsonArray([
                    'batch_id' => 'required|numeric',//批次id
                    'storage_manage_id' => 'required|numeric|',//库存id
                    'num' => 'required|numeric' //要使用的批次数量
                ])
            ],
            'id' => 'required|numeric',//销售单内商品或销售单内套餐商品id
            'sell_id' => 'required|numeric|', //销售单id
            'type' => [
                'required',
                Rule::In([0,1]),
            ],//条码类型0:商品;1:套餐;
        ],[
            'id.required' => '参数`销售单内商品或销售单内套餐商品id`缺失',
            'sell_id.required' => '参数`sell_id`缺失',
            'sell_id.numeric' => '参数`sell_id`类型错误',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
            'info.required' => '参数`info`缺失',
            'info.json' => '参数`info`仅能为json',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
//        $data['user_id'] = $this->getUserId();

        $this->log('设置批次号', $data);
        return response()->json(
            SellService::sellAddBatch($data)
        );
    }

    public function sellBatchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id'=>'required|integer',//销售单id
            'type' => [
                'required',
                Rule::In([0,1]),
            ],//条码类型0:商品;1:套餐;
            'materiel_type_id' => 'required|integer',//销售单id
        ], [
            'id.required' => '参数`sell_id`缺失',
            'id.integer' => '参数`sell_id`异常',
            'materiel_type_id.required' => '参数`商品id`类型错误',
            'materiel_type_id.integer' => '参数`商品id`异常',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            SellService::sellBatchList($data)
        );
    }

    /**
     * 编辑销售单内商品批次信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/7/2 16:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellBatchEdit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
//            'id'=>'required|integer',//销售单id
            'goods_batch_id'=>'required|integer',//销售单内商品或销售单内套餐商品批次id
            'type' => [
                'required',
                Rule::In([0,1]),
            ],//条码类型0:商品;1:套餐;
            'num' => 'required|min:0'
        ], [
            'goods_batch_id.required' => '参数`销售单内商品批次id`缺失',
            'goods_batch_id.integer' => '参数`销售单内商品批次id`异常',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
            'num.required' => '参数`数量`缺失',
            'num.min' => '参数`数量`最小只能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('编辑商品批次信息', $data);

        return response()->json(
            SellService::sellBatchEdit($data)
        );
    }

    public function sellBatchDel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_batch_id'=>'required|integer',//销售单内商品或销售单内套餐商品批次id
            'type' => [
                'required',
                Rule::In([0,1]),
            ],//条码类型0:商品;1:套餐;
        ], [
            'goods_batch_id.required' => '参数`销售单内商品批次id`缺失',
            'goods_batch_id.integer' => '参数`销售单内商品批次id`异常',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if($data['type'] == 0) {
            $sellGoodsDetailBatchInfo = SellGoodsDetailBatchModel::where('id', $data['goods_batch_id'])
                ->first();

            if(empty($sellGoodsDetailBatchInfo)) {
                return $this->fail('','目标商品批次不存在，无法操作');
            }

            if($sellGoodsDetailBatchInfo['num'] != $sellGoodsDetailBatchInfo['rest_num']) {
                return $this->fail('','目标商品批次已出库，无法删除');
            }

            SellGoodsDetailBatchModel::where('id', $data['goods_batch_id'])->delete();
        }
        else {
            $sellPackageBatchInfo = SellPackageBatchModel::where('id', $data['goods_batch_id'])->first();

            if(empty($sellPackageBatchInfo)) {
                return $this->fail('','目标商品批次不存在，无法操作');
            }

            if($sellPackageBatchInfo['num'] != $sellPackageBatchInfo['rest_num']) {
                return $this->fail('','目标商品批次已出库，无法删除');
            }

            SellPackageBatchModel::where('id', $data['goods_batch_id'])->delete();
        }

        $this->log('删除销售单内商品或销售单内套餐商品批次信息', $data);
        return $this->success();
    }

    /**
     * 销售单已有快递单号列表
     * @param Request $request
     * 2022/8/22 20:20
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellExpressInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer|min:1',//当前页
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`仅能为数字',
            'pageSize.min' => '`页面大小`仅能为1',
            'currentPage.required' => '`当前页大小`缺失',
            'currentPage.integer' => '`当前页`仅能为数字',
            'currentPage.min' => '`当前页`仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //是否共享
        $condition = [];
        if(!$this->isShareExpress()) {
            if($this->getUserTpye()) {
                $condition['user_id'] = ['EQ' => $this->getUserId()];
            }
            else {
                $condition['main_id'] = ['EQ' => $this->getMainUserId()];
            }
        }
        else {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }

        $keyword = isset($data['code'])?$data['code']:'';

        $model = SellModel::select('logistics_order_no', 'logistics_company')->where($condition)
            ->where('repeal_status', 0)
            ->where('delete_flag', 0)
            ->where('logistics_order_no', '!=', '')
            ->where('logistics_order_no', 'LIKE', '%'.$keyword.'%')
            ->orderBy('id','desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();

        return $this->success($model);
    }

    /**
     * 其他费用添加
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherCharges(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'required|string',//其他费用类型名称
            'other_remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        //开启事务
        DB::beginTransaction();
        try{
            SellOtherChargesModel::insert($data);
            $model = SellModel::where('id',$data['sell_id'])->first();
            $model->other_charges = $model->other_charges+$data['money'];
            $model->save();
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加其他费用');
        }
    }

    /**
     * 其他费用列表
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesList(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $model = SellOtherChargesModel::where('sell_id',$data['sell_id'])->get();
        return $this->success($model);
    }

    /**
     * 其他费用编辑
     * change 在 2021/11/2 14:41 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function otherChargesEdit(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//其他费用主键id
            'money' =>'required|string',//其他费用
            'other_type_name' =>'string',//其他费用类型名称
            'other_remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
        DB::beginTransaction();
        try{
            $beforeModel = SellOtherChargesModel::where('id',$data['id'])->first();
            SellOtherChargesModel::where('id',$data['id'])->update($data);
            $beforeMoney = $beforeModel['money'];
            $final = $data['money']-$beforeMoney;
            $model = SellModel::where('id',$beforeModel['sell_id'])->first();
            $model->other_charges = $model->other_charges+$final;
            $model->save();
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加其他费用');
        }
    }

    /**
     * 绑定司机(添加编辑)
     * change 在 2021/11/2 09:40 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindDriver(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'sell_id' =>'required|integer',//销售单主键id
            'plate_number' =>'required|string',//车牌
            'name' =>'required|string',//司机姓名
            'phone' =>'required|string',//提货司机电话
            'logistics_company' =>'string',//物流公司
            'remark' =>'string',//备注
            'plate_image' =>'string',//车牌照片
            'id_card_image' =>'string',//身份证照片
            'driving_licence' =>'string',//驾驶证照片
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['created_at'] = time();
        $model = SellDriverModel::where('sell_id',$data['sell_id'])->first();
        if($model){
            unset($data['created_at']);
            SellDriverModel::where('sell_id',$data['sell_id'])->update($data);
        }else{
            SellDriverModel::insert($data);
        }
        return $this->success();
    }

    public function sellSerialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'type_id' =>'required|integer',//其他费用主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            sellService::sellSerialList($data)
        );
    }
}
